<template>
	<view>

		<map id="map" scale="15" :longitude="from.longitude" :latitude="from.latitude" :enable-poi="true" class="map"
			:style="mapStyle" :polyline="polyline" :markers="markers" @longpress="showHandle">
			<!-- <cover-image class="location" src="../static/workbench/location.png" @tap="returnLocationHandle()" /> -->
			<cover-view class="information-container" v-show="infoStatus">
				<cover-image src="../static/move/close-icon.png" class="close-icon" @tap="hideHandle"></cover-image>
				<cover-view class="info">
					<cover-view class="label">剩余</cover-view>
					<cover-view class="value">{{ distance }}公里</cover-view>
					<cover-view class="label">，预计</cover-view>
					<cover-view class="value">{{ duration }}分钟</cover-view>
				</cover-view>
			</cover-view>
		</map>

	</view>
</template>

<script>
	let QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
	let qqmapsdk;
	export default {
		data() {
			return {
				map: null,
				mapStyle: '',
				infoStatus: true,
				from: {
					//当前司机坐标。应该实时获取定位.也是路线规划的开始位置
					longitude: 0, //uni.getStorageSync("location").longitude,
					latitude: 0, //uni.getStorageSync("location").latitude,
				},
				to: { //路线规划的结束位子
					longitude: 0,
					latitude: 0,
				},
				mode: "bicycling",
				//测距：距离和时长
				distance: 0,
				duration: 0,
				//路线测距的路线坐标点数组
				polyline: [],
				//图标
				markers: [],
				timer: null,
				//模拟数据
				isImitate: false,
				imitate: null
			};
		},
		methods: {
			//初始化
			init() {
				const _this = this;
				//处理窗口样式
				let windowHeight = uni.getSystemInfoSync().windowHeight;
				_this.windowHeight = windowHeight;
				_this.mapStyle = `height:${_this.windowHeight}px;`;
				//uniapp地图
				_this._map = uni.createMapContext("map", _this);
				//腾讯地图
				qqmapsdk = new QQMapWX({
					key: _this.Constants.QQMAP_KEY
				});
				uni.getLocation({
					type: 'wgs84', // 返回可以用于uni.openLocation的经纬度，默认为wgs84的gps坐标
					success: (res) => {
						_this.from.longitude = res.longitude;
						_this.from.latitude = res.latitude;
					},
					fail: (err) => {
						console.error('获取位置失败：', err);
					}
				});
			},
			//加载订单的位置
			loadOrderLocation() {
				let _this = this;
				if (!_this.orderNo) return;
				console.log("---开始加载订单位置---")
				//加载订单地址
				_this.get("/order/app/order/" + _this.orderNo, (res) => {
					const data = res.data;
					if (res.success) {
						console.log("---加载订单位置成功---")
						//根据订单状态，设置终点和驾车方式
						if (data.status == _this.Constants.OrderStatus.ORDER_STATUS_ACCEPTED) {
							console.log("---自行车---")
							//接单成功，去往订单开始位置
							_this.to.longitude = data.startPlaceLongitude;
							_this.to.latitude = data.startPlaceLatitude;
							//自行车
							_this.mode = "bicycling";
						} else if (data.status == _this.Constants.OrderStatus.ORDER_STATUS_ARRIVE ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_START_DRIVING) {
							console.log("---驾车---")
							//开始代驾，去往订单结束位置
							_this.from.longitude = data.startPlaceLongitude;
							_this.from.latitude = data.startPlaceLatitude;
							_this.to.longitude = data.endPlaceLongitude;
							_this.to.latitude = data.endPlaceLatitude;
							//驾车
							_this.mode = "driving";
						}else if(data.status == _this.Constants.OrderStatus.ORDER_STATUS_COMPLETE_DRIVED){
							_this.closeMove();
						}
						setTimeout(() => {
							_this.remarkers();
						}, 1000)
						//创建定时任务
						setTimeout(() => {
							_this.linePlan();
						}, 1000)
					}
				});
			},
			//标记点
			remarkers() {
				const _this = this;
				//绘制开始位置和结束位子的图标
				_this.markers = [{ //开始位置图标
						id: 1,
						longitude: _this.from.longitude,
						latitude: _this.from.latitude,
						title: "开始位置",
						iconPath: "../static/move/driver-icon.png",
						width: 32,
						height: 32
						//iconPath:"https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png"
					},
					{ //结束位置图标
						id: 2,
						latitude: _this.to.latitude,
						longitude: _this.to.longitude,
						title: "结束位置",
						iconPath: "../static/move/end.png",
						width: 25,
						height: 37
					}
				]
			},
			//路线规划
			linePlan() {
				let _this = this;
				qqmapsdk.direction({
					//模式：驾车
					mode: _this.mode,
					//路线规划开始位置
					from: _this.from,
					//路线规划结束位子
					to: _this.to,
					success: function(res) {
						console.log("---路线规划成功---");
						const ret = res;
						const coors = ret.result.routes[0].polyline,
							pl = [];
						//坐标解压（返回的点串坐标，通过前向差分进行压缩）
						const kr = 1000000;
						for (let i = 2; i < coors.length; i++) {
							coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
						};
						//将解压后的坐标放入点串数组pl中
						for (let i = 0; i < coors.length; i += 2) {
							pl.push({
								latitude: coors[i],
								longitude: coors[i + 1]
							})
						};
						//模拟数据
						if (uni.getStorageSync("workStatus") == _this.Constants.WORK_STATUS
							.RECEPTION_CUSTOMER ||
							uni.getStorageSync("workStatus") == _this.Constants.WORK_STATUS.START_DRIVING) {
							if (_this.isImitate == false) {
								_this.imitate = pl;
								_this.isImitate = true;
								_this.setInterval();
							}
						} else {
							uni.$emit('uploadDriverLocation2Geo', _this.from.longitude, _this.from.latitude);
						};
						//设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
						_this.polyline = [{
							points: pl,
							color: '#FF0000DD',
							width: 4
						}];
						_this.distance = (res.result.routes[0].distance / 1000).toFixed(2);
						_this.duration = res.result.routes[0].duration;
					},
					fail: function(error) {
						console.error(error);
					}
				});
			},
			//开启定时器-- 定时去查询司机位置
			setInterval() {
				const _this = this;
				if (_this.pullOrderTimer) {
					return;
				}
				let index = 0; // 起始索引
				const step = 10; // 每次跳跃的步长
				_this.timer = setInterval(() => {
					console.log("定时器2执行了")
					if (index >= _this.imitate.length || index + step >= _this.imitate.length) {
						index = _this.imitate.length - 1; // 选择最后一个点
						console.log(uni.getStorageSync("workStatus"));
						_this.updateLocation(index); // 更新位置
						setTimeout(() => {
							if (uni.getStorageSync("workStatus") == _this.Constants.WORK_STATUS
								.RECEPTION_CUSTOMER) {
								uni.$emit("arriveStartPlaceHandle");
							} else if (uni.getStorageSync("workStatus") == _this.Constants.WORK_STATUS
								.START_DRIVING) {
								uni.$emit("endDrivingHandle");
							}
						}, 2000);
						clearInterval(_this.timer); // 停止定时器
						_this.timer = null; // 重置计时器变量
						_this.isImitate = false; // 重置是否模拟
						_this.imitate = null; // 重置模拟数组
						setTimeout(() => {
							_this.loadOrderLocation();
						}, 2000);
						return;
					}
					// 正常情况下更新索引并更新位置
					_this.updateLocation(index); // 更新位置
					index += step; // 更新索引
				}, 5000)
			},
			updateLocation(index) {
				const _this = this;
				_this.from.longitude = _this.imitate[index].longitude;
				_this.from.latitude = _this.imitate[index].latitude;
				uni.$emit('uploadDriverLocation2Geo', _this.from.longitude, _this.from.latitude);
				_this.remarkers();
				_this.linePlan();
			},
			hideHandle() {
				this.closeMove();
			},
			//关闭当前页面
			closeMove() {
				uni.navigateBack();
			}
		},
		onLoad(options) {
			const _this = this;
			_this.orderNo = options.orderNo;
			_this.init();
			uni.$on('closeMove', this.closeMove);
		},
		onShow() {
			const _this = this;
			_this.loadOrderLocation();
		},
		onHide() {
			console.log("关闭定时器")
			clearInterval(this.timer);
		},
		onUnload() {
			console.log("关闭定时器")
			clearInterval(this.timer);
			uni.$off('closeMove', this.closeMove);
		},
	};
</script>

<style lang="less">
	@import url('move.less');
</style>